"""
RagFlow 客户端 GUI 日志选项卡组件
"""

from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout,
    QTextEdit, QPushButton
)


class LogTabWidget(QWidget):
    """日志选项卡组件"""
    
    def __init__(self, parent=None):
        """初始化日志选项卡组件"""
        super().__init__(parent)
        self.parent = parent
        self.setup_ui()
    
    def setup_ui(self):
        """创建界面"""
        # 创建布局
        layout = QVBoxLayout(self)
        
        # 创建日志文本框
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        layout.addWidget(self.log_text)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        layout.addLayout(button_layout)
        
        # 清空日志按钮
        clear_button = QPushButton("清空日志")
        clear_button.clicked.connect(self.clear_log)
        button_layout.addWidget(clear_button)
        
        # 保存日志按钮
        save_button = QPushButton("保存日志")
        save_button.clicked.connect(self.save_log)
        button_layout.addWidget(save_button)
        
        # 添加弹性空间
        button_layout.addStretch()
    
    def clear_log(self):
        """清空日志"""
        self.log_text.clear()
    
    def save_log(self):
        """保存日志"""
        from PySide6.QtWidgets import QFileDialog
        
        # 获取保存路径
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存日志", "", "文本文件 (*.txt);;所有文件 (*)"
        )
        
        if file_path:
            try:
                # 保存日志
                with open(file_path, "w", encoding="utf-8") as f:
                    f.write(self.log_text.toPlainText())
                
                # 提示用户
                from PySide6.QtWidgets import QMessageBox
                QMessageBox.information(self, "成功", f"日志已保存到: {file_path}")
            except Exception as e:
                from PySide6.QtWidgets import QMessageBox
                QMessageBox.critical(self, "错误", f"保存日志失败: {str(e)}")
    
    def append_log(self, text):
        """
        添加日志
        
        Args:
            text: 日志文本
        """
        self.log_text.append(text)